#Represents a slideshow image with its duration and position in slideshow.
class SlideshowImage < ActiveRecord::Base 
  belongs_to :slideshow
  
  file_column :image_url, :magick => { 
    :geometry => '390x286',
    :versions => {'thumb' => '50x30'} 
  }

  #Calls parent constructor and sets the position and duration fields
  def initialize(hash)
    super(hash)
    self.position = slideshow.next_position
    self.duration = 5
  end
  
  #Returns slideshow images that follow this one in the slideshow.
  def successors
    SlideshowImage.find(:all, :conditions => ['slideshow_id = ? AND position > ?', slideshow_id, position])
  end
  
  #Executes actions before destroying slideshow image.
  def before_destroy
    #Update all successive slide's positions
    successors.each{|s| s.update_attribute(:position, s.position-1)}
  end
  
  validates_presence_of :slideshow_id,  :image_url, :position, :duration  
  validates_format_of :image_url, 
  :with    => %r{\.(gif|jpg|png|swf)$}i,
  :message => "must be a URL for a GIF, JPG, PNG or SWF file"
  
end
